package com.asiainfo.dacp.datastash.worker.executor.adapter.datax.translate.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.asiainfo.dacp.crypto.Crypto;
import com.asiainfo.dacp.crypto.cipher.AesCipher;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.CommonErrorCode;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.Configuration;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.WorkerException;
import com.asiainfo.dacp.metamodel.domain.ds.model.MetaDataSource;
import com.asiainfo.dacp.metamodel.domain.ds.repo.MetaDataSourceRepository;
import com.google.common.base.Strings;

@Service
public class DataSourceStrategyFromDB implements DataSourceStrategy{
	private static final Logger LOG = LoggerFactory.getLogger(DataSourceStrategyFromDB.class);

	@Autowired
	private MetaDataSourceRepository dsRepository; 


	@Override
	public MetaDataSource getDataSource(Configuration conf) {
		MetaDataSource dbDs = null;
		String dsName = conf.getNecessaryValue("dsName", CommonErrorCode.CONFIG_ERROR);
		try {
			//dbDs = dsRepository.findOne(dsId);
			dbDs = dsRepository.findByName(dsName);
			LOG.info("\nMetaDataSource : {}" , JSON.toJSONString(dbDs, SerializerFeature.PrettyFormat));
			//加密
			String password = dbDs.getDsAuth();
			if(!Strings.isNullOrEmpty(password)){
				try{
					dbDs.setDsAuth(AesCipher.decrypt(password, Crypto.DEFAULT_SECRET_KEY));
				}catch(Exception e){
					LOG.warn(String.format("DB数据源 [%s]，解密失败 .", dsName));
				}
			}
		} catch (Exception e) {
			throw WorkerException.asDataXException(CommonErrorCode.RUNTIME_ERROR,
					String.format("未获取到DB数据源 [%s]，检查表 dacp_meta_datasource .", dsName), e);
		}
		return dbDs;
	} 
}
